package com.zgw.fireline.base.controls;

import java.util.EventObject;

import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;

import com.zgw.fireline.base.common.Assert;
import com.zgw.fireline.base.dataset.Dataset;
import com.zgw.fireline.base.dataset.DatasetListener;

/**
 * Dataset Combo
 * */
public class DataCombo extends Combo {

	private final Dataset dataset;
	private String showText; // 在 对应的数据集中指定文本作为显示值.
	private String valueColumn;// 在 对应的数据集中指定一列作为实际值.

	public DataCombo(Composite parent, int style, Dataset set) {
		super(parent, style);
		this.dataset = set;
		if (dataset != null) {
			addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					Integer index = (Integer) getData(getText());
					dataset.setSelected(index);
				}
			});
			final DatasetListener listener = new DatasetListener() {
				public void rowSetChanged(EventObject event) {
					refresh();
				}

				public void rowChanged(EventObject event) {

				}

				public void cursorMoved(EventObject event) {
					for (String i : getItems()) {
						Integer index = (Integer) getData(i);
						if (index.equals(dataset.getSelectedIndex())) {
							setText(i);
							break;
						}
					}
				}
			};
			dataset.addDatasetListener(listener);
			addDisposeListener(new DisposeListener() {
				public void widgetDisposed(DisposeEvent e) {
					dataset.removeDatasetListener(listener);
				}
			});
		}
	}

	public Dataset getDataset() {
		return dataset;
	}

	public String getShowText() {
		return showText;
	}

	public void setShowText(String showText) {
		if (!showText.equals(this.showText)) {
			this.showText = showText;
			refresh();
		}
	}

	public String getValueColumn() {
		return valueColumn;
	}

	public void setValueColumn(String valueColumn) {
		this.valueColumn = valueColumn;
	}

	public void setValue(Object value) {

	}

	/** 获取选中项值 */
	public Object getValue() {
		return null;
	}

	public void refresh() {
		if (dataset != null) {
			removeAll();
			String nullItem = ""; // 空项
			add(nullItem);
			setData(nullItem, -1);
			setText(nullItem);
			if (dataset.getCount() > 0) {
				Assert.isNotNull(showText, "无法构建下拉框项,未设置 showText");
			}
			for (int i = 0; i < dataset.getCount(); i++) {
				String text = dataset.getStringForExpr(i, showText);
				add(text);
				setData(text, i);
				if (i == dataset.getSelectedIndex()) {
					setText(text);
				}
			}
		}
	}

	@Override
	protected void checkSubclass() {
	}
}
